#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include <unistd.h>

#define COPYMODE	0644
#define BUFFERSIZE	4096

int main(int argc, char* argv[]) {
	int out_fd, in_fd, n_chars;
	char buf[BUFFERSIZE];
	//1. check args
	if(argc != 3) {
		fprintf(stderr, "Usage: %s source destination",argv[0]);
		exit(EXIT_FAILURE);
	}

	//2. open file
	if((out_fd = open(argv[1], O_RDONLY)) == -1) {
		fprintf(stderr, "Error open %s",argv[1]);
		exit(EXIT_FAILURE);
	}

	//3. create file
	if((in_fd = creat(argv[2], COPYMODE)) == -1) {
		fprintf(stderr, "Error creat %s",argv[2]);
		exit(EXIT_FAILURE);
	}

	//4. read and write
	while((n_chars = read(out_fd, buf, BUFFERSIZE)) > 0) {
		if( write(in_fd, buf, n_chars) != n_chars) {
			fprintf(stderr, "Error write %s",argv[2]);
			exit(EXIT_FAILURE);
		}
	}

	if(n_chars == -1) {
		fprintf(stderr, "Error read %s",argv[1]);
		exit(EXIT_FAILURE);
	}

	//5. close file
	if(close(in_fd) == -1 || close(out_fd) == -1) {
		fprintf(stderr, "Error close files");
		exit(EXIT_FAILURE);
	}		
}

